/**
 * @file device_state.c
 * @author your name (you@domain.com)
 * @brief
 * @version 0.1
 * @date 2024-02-27
 *
 * @copyright Copyright (c) 2024
 *
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "device_state.h"
#include "FreeRTOS.h"
#include "task.h"
#include "log.h"
#include "aiio_system.h"
#include "aiio_wifi.h"
#include "wifi_mgmr_ext.h"


#define DBG_TAG "DEVICE_STATE"

static TaskHandle_t device_task_handle;

static homeAssisatnt_device_t ha_device;
static ip_addr_t dns_addr;
static void device_state_task(void* arg);
static void ha_event_cb(ha_event_t event, homeAssisatnt_device_t* ha_dev);

void device_state_init(void)
{
    uint8_t STA_MAC[6] = { 0 };
    //配网按键初始化
    device_rgb_init();
    device_button_init(CONFIG_BUTTON);
    staWiFiInit();
    aiio_wifi_sta_mac_get(STA_MAC);
    ha_device.mqtt_info.mqtt_username = pvPortMalloc(128);
    memset(ha_device.mqtt_info.mqtt_username, 0, 128);
    sprintf(ha_device.mqtt_info.mqtt_username, "Ai-M62_Buld-%02X%02X", STA_MAC[4], STA_MAC[5]);
    ha_device.name = ha_device.mqtt_info.mqtt_username;
    ha_device.mqtt_info.mqtt_keeplive = 60;
    ha_device.model = "Ai-M62-Buld";
    ha_device.mqtt_info.mqtt_clientID = ha_device.model;
    ha_device.hw_version = "Ai-M62-12F_V1.0";
    ha_device.identifiers = "aipi_m62_cbs_v10";
    homeAssistant_device_init(&ha_device, ha_event_cb);
    xTaskCreate(device_state_task, "device_state_task", 1024*2, NULL, 14, &device_task_handle);
#if (CONFIG_NETWORK_TYPE==CONFIG_BUTTON)
    device_update_state(DEVICE_STATE_INIT_OK, false);
#endif
}

void device_update_state(dev_state_t new_state, uint8_t is_irq)
{
    BaseType_t xHigherPriorityTaskWoken;
    if (device_task_handle==NULL)return;
    if (is_irq) {
        xTaskNotifyFromISR(device_task_handle, new_state, eSetValueWithoutOverwrite, &xHigherPriorityTaskWoken);
    }
    else {
        xTaskNotify(device_task_handle, new_state, eSetValueWithoutOverwrite);
    }
}

static void device_state_task(void* arg)
{
    dev_state_t state;
    char* flash_ssid = NULL;
    char* flash_pass = NULL;
    char* bssid = NULL;

    dns_init();

    while (1) {
        xTaskNotifyWait(0, 0xffffffff, &state, portMAX_DELAY);
        switch (state)
        {
            case DEVICE_STATE_INIT_OK:
            {
                device_rgb_wifi_config_light_start(CONFIG_RGB_GREEN_PIN);
                //读取flas  
                uint8_t len = 32;
                flash_ssid = flash_get_data(CONFIG_FLASH_KEY_SSID, len);
                //读不到SSID，开启配网
                if (strlen(flash_ssid)==0) {
                    homeassistant_blufi_start();
                    break;
                }
                //读到直接连接
                len = 64;
                flash_pass = flash_get_data(CONFIG_FLASH_KEY_PWD, len);
                len = 6;
                bssid = flash_get_data(CONFIG_FLASH_KEY_BSSID, len);
                staWiFiConnect(flash_ssid, flash_pass, bssid);
                //初始化

            }
            break;
            case DEVICE_STATE_BLUFI_STATR:
            {
                LOG_I("DEVICE_STATE_BLUFI_STATR");
                flash_erase_data(CONFIG_FLASH_KEY_SSID);
                flash_erase_data(CONFIG_FLASH_KEY_PWD);
                flash_erase_data(CONFIG_FLASH_KEY_BSSID);
                vTaskDelay(pdMS_TO_TICKS(500));
                GLB_SW_System_Reset();
            }
            break;
            case DEVICE_STATE_WIFI_INIT_OK:
                update_homeassistant_blufi_event(BLUFI_STATION_CONNECTED);
                break;
            case DEVICE_STATE_WIFI_CONNECT_OK:
                update_homeassistant_blufi_event(BLUFI_STATION_GOT_IP);
                inet_aton("223.5.5.5", &dns_addr.addr);
                dns_setserver(0, &dns_addr);

                homeAssistant_device_start();

                aiio_wifi_sta_connect_ind_stat_info_t sta_info;
                aiio_wifi_sta_connect_ind_stat_get(&sta_info);

                flash_erase_set(CONFIG_FLASH_KEY_SSID, sta_info.ssid);
                flash_erase_set(CONFIG_FLASH_KEY_PWD, sta_info.passphr);
                flash_erase_set(CONFIG_FLASH_KEY_BSSID, sta_info.bssid);
                // flash_erase_set(CONFIG_RESET_NUBLE, "0");

                LOG_I("Save ssid=%s,password=%s,bssid=%02x:%02x:%02x:%02x:%02x:%02x", sta_info.ssid, sta_info.passphr, sta_info.bssid[0], sta_info.bssid[1], sta_info.bssid[2], sta_info.bssid[3], sta_info.bssid[4], sta_info.bssid[5]);
                break;
            case DEVICE_STATE_WIFI_DISCONNECT:
                update_homeassistant_blufi_event(BLUFI_STATION_DISCONNECTED);
                break;
            case DEVICE_STATE_MQTT_CONNECT:
                device_rgb_wifi_config_light_stop();
                if (flash_ssid!=NULL) vPortFree(flash_ssid);
                if (flash_pass!=NULL) vPortFree(flash_pass);
                if (bssid)vPortFree(bssid);
                break;
            default:
                break;
        }
    }
}

static void ha_event_cb(ha_event_t event, homeAssisatnt_device_t* ha_dev)
{
    switch (event)
    {
        case HA_EVENT_MQTT_CONNECED:
            LOG_I("<<<<<<<<<<  HA_EVENT_MQTT_CONNECED");
            device_update_state(DEVICE_STATE_MQTT_CONNECT, false);
            static ha_lh_entity_t entity_rgb1 = {
               .name = "RGB灯",
               .unique_id = "DU_rgb",
               .rgb.rgb_command_topic = "m62/rbg/set",
               .rgb.rgb_state_topic = "m62/rgb/state",
               .rgb.red = 64,
               .rgb.green = 48,
               .rgb.blue = 35,
            };
            red_buff = entity_rgb1.rgb.red;
            green_buff = entity_rgb1.rgb.green;
            blue_buff = entity_rgb1.rgb.blue;

            homeAssistant_device_add_entity(CONFIG_HA_ENTITY_LIGHT, &entity_rgb1);
            homeAssistant_device_send_status(HOMEASSISTANT_STATUS_ONLINE);
            homeAssistant_device_send_entity_state(CONFIG_HA_ENTITY_LIGHT, ha_dev->entity_light->light_list->next, true);
            break;
        case HA_EVENT_MQTT_DISCONNECT:
            LOG_I("<<<<<<<<<<  HA_EVENT_MQTT_DISCONNECT");
            device_update_state(DEVICE_STATE_MQTT_DISCONNECT, false);
            break;
        case HA_EVENT_MQTT_COMMAND_LIGHT_SWITCH:
            LOG_I("<<<<<<<<<<   HA_EVENT_MQTT_COMMAND_LIGHT_SWITCH %s", ha_dev->entity_light->command_light->light_state?"ON":"OFF");

            homeAssistant_device_send_entity_state(CONFIG_HA_ENTITY_LIGHT, ha_dev->entity_light->command_light, ha_dev->entity_light->command_light->light_state);

            if (ha_dev->entity_light->command_light!=NULL)
                device_rgb__inch_by_update_color(ha_dev->entity_light->command_light->light_state?ha_dev->entity_light->command_light->rgb.red:0,
                ha_dev->entity_light->command_light->light_state?ha_dev->entity_light->command_light->rgb.green:0,
                ha_dev->entity_light->command_light->light_state?ha_dev->entity_light->command_light->rgb.blue:0, 20, 20);
            if (!ha_dev->entity_light->command_light->light_state) {
                device_rgb_update_color(0, 0, 0);
                red_buff = 0;
                green_buff = 0;
                blue_buff = 0;
            }
            break;
        case HA_EVENT_MQTT_COMMAND_LIGHT_RGB_UPDATE:
            LOG_I("<<<<<<<<<<   HA_EVENT_MQTT_COMMAND_LIGHT_RGB_UPDATE,RGB=%d,%d,%d", ha_dev->entity_light->command_light->rgb.red, ha_dev->entity_light->command_light->rgb.green, ha_dev->entity_light->command_light->rgb.blue);
            // device_rgb_update_color(ha_dev->entity_light->command_light->rgb.red, ha_dev->entity_light->command_light->rgb.green, ha_dev->entity_light->command_light->rgb.blue);
            homeAssistant_device_send_entity_state(CONFIG_HA_ENTITY_LIGHT, ha_dev->entity_light->command_light, ha_dev->entity_light->command_light->light_state);
            device_rgb__inch_by_update_color(ha_dev->entity_light->command_light->rgb.red, ha_dev->entity_light->command_light->rgb.green, ha_dev->entity_light->command_light->rgb.blue, 20, 20);

            break;
        default:
            break;
    }
}
